using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using webapi.Models;
using webapi.Models.Database;

namespace webapi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CategoryController : ControllerBase
    {
        // 构造方法注入
        private readonly CnewsContext _context;
        public CategoryController(CnewsContext context)
        {
            _context = context;
        }

        // 获取分类列表
        /// <summary>
        /// 获取分类列表
        /// </summary>
        [HttpGet]
        public List<Category> GetCategoryList()
        {
            return _context.Categories.ToList();
        }

        // 创建分类
        /// <summary>
        /// 创建分类
        /// </summary>
        [HttpPost]
        public string CreateCategory(string cateName)
        {
            // 判断参数是否合法
            if (!ModelState.IsValid)
            {
                return "参数错误";
            }

            // 业务逻辑
            // 判断数据库中是否存在该分类
            if (_context.Categories.Where(c => c.CateName == cateName).Count() > 0)
            {
                return "分类已存在";
            }

            // 实例化Category类，然后将传递的参数赋值给Category类
            var model = new Category();
            model.CateName = cateName;
            model.CateId = _context.Categories.Max(c => c.CateId) + 1;
            _context.Categories.Add(model);
            if (_context.SaveChanges() > 0)
            {
                return "创建成功";
            }
            return "创建失败";
        }

        //删除分类
        /// <summary>
        /// 删除分类
        /// </summary>
        [HttpPost]
        public string DeleteCategory(int cateId)
        {
            // 判断参数是否合法
            if (!ModelState.IsValid)
            {
                return "参数错误";
            }

            // 业务逻辑
            // 判断数据库中是否存在该分类
            if (_context.Categories.Where(c => c.CateId == cateId).Count() == 0)
            {
                return "分类不存在";
            }

            // 实例化Category类，然后将传递的参数赋值给Category类
            var model = new Category();
            model.CateId = cateId;
            _context.Categories.Remove(model);
            if (_context.SaveChanges() > 0)
            {
                return "删除成功";
            }
            return "删除失败";
        }
    }

}